package com.sdi.columbus;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Calendar;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TimePicker;
import android.widget.Toast;

@SuppressLint("ValidFragment")
public class GetReportDate extends FragmentActivity {

//	int VehicleId;
	String VehicleId;
	EditText e1,e2,e3,e4;
	ImageButton m1,m2,m3,m4;
	Button report,b1,b2,b3,b4;
	String sd,st,ed,et;
	Intent news,newss;
	Bundle bun,forrep;
	String stime,etime,responses,reports,runningtime,duration,accountID;
	int MaxSpeed,MinSpeed,distance;
	private static Double green;
	GetReport get;
	String startdate,enddate,formatedDate,starttime,endtime;
	DatePicker dp1;
	TimePicker tp1; 
	int day,month,year;
	int hour,minute;
	int idd,idt;
	int yyyy,mm,dd,hr,hr2;
	DecimalFormat mFormat;
	String dampm;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.getdate_report);
		
		Intent in=getIntent();
		Bundle bun=in.getExtras();
		accountID=ColombusApp.getSharedApp().accountId;
		//VehicleId=bun.getInt("vehicleids");
		VehicleId=bun.getString("vehicleids");
		
		
		System.out.println("vehicle id got frm report is"+VehicleId);
		
		
		final Calendar c = Calendar.getInstance();
	    yyyy = c.get(Calendar.YEAR);
	    mm = c.get(Calendar.MONTH);
	    dd = c.get(Calendar.DAY_OF_MONTH);
	    
	    mFormat= new DecimalFormat("00");
	    
	    formatedDate=mFormat.format(Double.valueOf(dd))+"-"+mFormat.format(Double.valueOf(mm+1))+"-"+yyyy;
		
		e1=(EditText)findViewById(R.id.frm1);
		e2=(EditText)findViewById(R.id.frm2);
		e3=(EditText)findViewById(R.id.to1);
		e4=(EditText)findViewById(R.id.to2);
		//e1.setTextColor(51153204);
        e1.setText(formatedDate);
		e3.setText(formatedDate);
	
		e2.setText("12:00 AM");
		e4.setText("11:59 PM");
		sd=(mm+1)+"-"+dd+"-"+yyyy;
		ed=(mm+1)+"-"+dd+"-"+yyyy;
		st="00:00";
		et="23:59";
		
		
		//m1=(ImageButton)findViewById(R.id.imgb1);
        e1.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v1) {
				// TODO Auto-generated method stub
				selectDate(v1);
			}
		});
        
        
        
		
        e2.setOnClickListener(new OnClickListener() {
			
			public void onClick(View vt1) {
				// TODO Auto-generated method stub
				showTimePickerDialog(vt1);
			}
		});
      
		
		
		
		 e3.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v2) {
					// TODO Auto-generated method stub
					selectDate(v2);
				}
			});
	        
	        e4.setOnClickListener(new OnClickListener() {
				
				public void onClick(View vt2) {
					// TODO Auto-generated method stub
					showTimePickerDialog(vt2);
				}
			});
        
       
		report=(Button)findViewById(R.id.rep);
		report.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				
				report.setBackgroundColor(Color.parseColor("#4099ff"));
				startdate=sd+" "+st;
				enddate=ed+" "+et;
				check();
				
				
				
			}
		});
		
		
	}
	public void check()
	{
		 get=new GetReport();
	    	
			try {
				responses=get.GetValues(accountID,VehicleId,startdate,enddate);
				JSONObject json = new JSONObject(responses);
				reports= json.getString("GetTripSummaryResult");
				System.out.println("first report"+reports);
				
				JSONObject json1 = new JSONObject(reports);
				
				System.out.println("starttime is"+startdate);
				System.out.println("endtime is"+enddate);
				MaxSpeed=Integer.parseInt(json1.getString("MaximumSpeed"));
				MinSpeed=Integer.parseInt(json1.getString("MinimumSpeed"));
				runningtime=json1.getString("TotalRunningTime");
				distance=Integer.parseInt(json1.getString("TotalDistance"));
				green=Double.parseDouble(json1.getString("GreenDriveIndex"));
				duration=json1.getString("TotalDuration");
				accountID=ColombusApp.getSharedApp().accountId;
				
//				---------------------------------------------------------------------------------------------------------------
				if(MaxSpeed==0 && MinSpeed==0 && distance==0 && green==0.0 && duration.equalsIgnoreCase("null")&& runningtime.equalsIgnoreCase("null"))
		        {
		        	System.out.println("enters if check");
		        	Toast.makeText(getBaseContext(), "Sorry No GPS data is available for the vehicle or the date is invalid", Toast.LENGTH_LONG).show();
		        	
		        }	
				else
				{
					news=new Intent(GetReportDate.this,DisplayReport.class);
					forrep=new Bundle();
//					forrep.putInt("vehicleids", VehicleId);
					forrep.putString("accoutID", accountID);
					forrep.putString("vehicleids", VehicleId);
					forrep.putString("start", startdate);
					forrep.putString("end",enddate);
					news.putExtras(forrep);
					new performBackgroundTask().execute();
					//startActivity(news);
					
				}
				
				
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
	}
	public void selectDate(View v) {
        DialogFragment newFragment = new SelectDateFragment();
        newFragment.show(getSupportFragmentManager(), "DatePicker");
        if(v==e1)
        {
        	idd=1;
        	
        }
        else if(v==e3)
        {
        	idd=2;
        	
        }
    }
	public void showTimePickerDialog(View v) {
	    DialogFragment newFragment = new TimePickerFragment();
	    newFragment.show(getSupportFragmentManager(), "timePicker");
	    
	    if(v==e2)
	    {
	    	idt=1;
	    }
	    else if(v==e4)
	    {
	    	idt=2;
	    }
	}
	
	public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
    	@Override
    	public Dialog onCreateDialog(Bundle savedInstanceState) {
			final Calendar calendar = Calendar.getInstance();
			int yy = calendar.get(Calendar.YEAR);
			int mm = calendar.get(Calendar.MONTH);
			int dd = calendar.get(Calendar.DAY_OF_MONTH);
			return new DatePickerDialog(getActivity(), this, yy, mm, dd);
    	}
    	
    	public void onDateSet(DatePicker view, int yy, int mm, int dd) {
    		populateSetDate(yy, mm+1, dd);
    	}
    	
    	 public void populateSetDate(int year, int month, int day) {
    	    	
    		 if(idd==1)
    		 {
    	    	e1.setText(mFormat.format(Double.valueOf(day))+"-"+mFormat.format(Double.valueOf(month))+"-"+year);
    	    	sd=month+"-"+day+"-"+year;
    	    }
    		 else if(idd==2)
    		 {
     	    	e3.setText(mFormat.format(Double.valueOf(day))+"-"+mFormat.format(Double.valueOf(month))+"-"+year);
     	    	ed=month+"-"+day+"-"+year;
     	    }
    	 }
	}
	
	
	
	public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener{
		@Override
	    public Dialog onCreateDialog(Bundle savedInstanceState) {
	        // Use the current time as the default values for the picker
	        final Calendar c = Calendar.getInstance();
	        hour = c.get(Calendar.HOUR_OF_DAY);
	        minute = c.get(Calendar.MINUTE);
	        

	        // Create a new instance of TimePickerDialog and return it
	        return new TimePickerDialog(getActivity(), this, hour, minute,false);
	    }

		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			// TODO Auto-generated method stub
			populateSetTime(hourOfDay,minute);
			
		}
        public void populateSetTime(int hour, int minute) {
        	if(idt==1)
   		 {
        		dampm="AM";
        		if(hour>12)
        		{
        			   hr=hour-12;
        			   dampm="PM";
        			   
        		}
        		else if(hour==12)
       			{
       				dampm="PM";
       				hr=hour;
       			}
        		else if(hour==0)
    			{
    			  hr=12;
    			  dampm="AM";
    			}
        		else
        		{		
        		hr=hour;
        		}
        		e2.setText(mFormat.format(Double.valueOf(hr))+":"+mFormat.format(Double.valueOf(minute))+" "+dampm);
        		st=hour+":"+minute;
        		System.out.println("hour"+hour);
   	    }
   		 else if(idt==2)
   		 {
   			dampm="AM";
   			if(hour>12)
    		{
   						
    			hr=hour-12;
    			dampm="PM";
    		}
   			else if(hour==0)
			{
			  hr=12;
			  dampm="AM";
			}
   			 else if(hour==12)
   			{
   				dampm="PM";
   				hr=hour;
   			}
   			else
   			{
   			hr=hour;
   			}
   			e4.setText(mFormat.format(Double.valueOf(hr))+":"+mFormat.format(Double.valueOf(minute))+" "+dampm);
   			et=hour+":"+minute;
   			System.out.println("hour"+hour);
    	    }
	    	
	    }
    	} 
    	
	private class performBackgroundTask extends AsyncTask < Void, Void, Void > 
    {
		
       private ProgressDialog pdia;

       @Override
       protected void onPreExecute(){
          super.onPreExecute();
               pdia = new ProgressDialog(GetReportDate.this);
               pdia.setMessage("Please Wait....");
               pdia.show();
               System.out.println("In onPreExecute");         
       }
 
       @Override
       protected Void doInBackground(Void... params) {
    	   
    	   System.out.println("In doInBackground");
    	   startActivity(news);
    	   return null;
    
       }

       @Override
       protected void onPostExecute(Void result) {
    	   super.onPostExecute(result);
    	   System.out.println("In onPostExecute");
    	   pdia.dismiss();
       }

       @Override
       protected void onProgressUpdate(Void... values) {
    	   super.onProgressUpdate(values);
    	   System.out.println("In onProgressUpdate");
       }

    }
	
	
	}

